package com.huike.service.impl;

import cn.hutool.core.bean.BeanException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.core.page.TableDataInfo;
import com.huike.dto.ActivityDto;
import com.huike.dto.domain.Activity;
import com.huike.mapper.ActivityMapper;
import com.huike.service.IActivityService;
import com.huike.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.time.LocalDateTime.now;
@Slf4j
@Service
public class
ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
@Autowired
private ActivityMapper activityMapper ;
private static final int NUMBER=2;
// 定义包含所有大小写字母和数字的字符池
    private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final SecureRandom random = new SecureRandom();
/*分页查询活动表*/
    @Override
    public TableDataInfo getActivityList(ActivityDto activityDto) {
/*分页参数*/
        TableDataInfo tableDataInfo = new TableDataInfo();



        Page<Activity> page= Page.of(activityDto.getPageNum(),activityDto.getPageSize());
        // 2. 添加倒序排序条件（假设按create_time字段排序）
       page.addOrder(OrderItem.desc("create_time"));
       log.info("开始拆分时间");
        HashMap<String, String> params = activityDto.getParams();

       String time=params.get("beginTime");
     String   createTime=params.get("beginCreateTime");
        //*判断条件的创立
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(Objects.nonNull(activityDto.getChannel()),Activity::getChannel,activityDto.getChannel())
        .eq(StringUtils.isNotEmpty(activityDto.getCode()) ,Activity::getCode,activityDto.getCode());
        // 创建时间范围查询
        if ( createTime != null && !"".equals(params.get("beginCreateTime"))) {
            // 完整时间范围
            LocalDate beginCreateTime = LocalDate.parse(params.get("beginCreateTime"));
            LocalDate endCreateTime = LocalDate.parse(params.get("endCreateTime"));
            wrapper.between(Activity::getCreateTime, beginCreateTime, endCreateTime);
        }
// 活动开始时间范围查询
        if ( time!= null &&  !"".equals(params.get("beginTime"))) {
            LocalDate beginTime = LocalDate.parse( params.get("beginTime"));
            LocalDate endTime = LocalDate.parse(params.get("endTime"));
            // 完整时间范围
            wrapper.between(Activity::getBeginTime,beginTime , endTime);
        }
        /*查询数据*/
     super.page(page,wrapper);
     /*返回数值*/
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal((int)page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return  tableDataInfo;
    }
/*新增方法*/
    @Override
    public void addActivitySe(Activity activity) {
/*begin_time(入参)  channel(入参)  create_by  create_time  discount(入参)  end_time(入参)
*id   info(入参)   name(入参)  status   type(入参)   code
*没有数据的是  create_by(返回数据没有)    create_time  id （数据库自增）  status   code
* */
//填入创建时间
        LocalDateTime createTime=now();
        activity.setCreateTime(createTime);
//        填入状态数字
        activity.setStatus(NUMBER+"");
//        创建一串随机数字作为code
        StringBuilder stCode = new StringBuilder(NUMBER*NUMBER*NUMBER);
        for (int i = 0; i < 8; i++) {
            // 从字符池中随机选取一个字符
            int randomIndex = random.nextInt(CHAR_POOL.length());
            stCode.append(CHAR_POOL.charAt(randomIndex));
        }
        String code = stCode.toString();
        activity.setCode(code);
//        判断项目名字是否相同
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Activity::getName);
        List<Object> names = activityMapper.selectObjs(wrapper);
        // 返回 List<Object>name集合
// 将 Object 转为目标类型（此处为 String）
        List<String> nameList = names.stream()
                .map(obj -> (String) obj)
                .collect(Collectors.toList());
String name=activity.getName();
        if (StringUtils.isNotEmpty(name)) {
            for(String activityName:nameList){
                if(!activityName.equals(name)){
                    throw new BeanException("活动名字重复");
                }
            }
        }
//        添加到数据库
        super.save(activity);
    }
    /*删除方法*/
    @Override
    public void deleteActivitySe(Integer id) {
super.removeById(id);
    }
/*修改方法*/
    @Transactional
    @Override
    public void updateActivitySe(Activity activity) {
//修改，先删除后添加
//        先删除
        int id=activity.getId();
        deleteActivitySe(id);
//        后添加
        addActivitySe(activity);
    }
/*点进修改后的回显数据*/
    @Override
    public Activity inquireActivitySe(Integer id) {

        Activity activity = activityMapper.selectById(id);

        return activity ;
    }
/*根据活动类型线上活动和推广活动，回显活动个数*/
    @Override
    public List<Activity> agreeActivityListSe(String  channel ) {
        log.info("来到service{}",channel);
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(channel),Activity::getChannel,channel);
        List<Activity> activities = activityMapper.selectList(wrapper);
        return  activities;
    }
}
